using Microsoft.Win32;
using MinoChat.Enums;
using MinoChat.Services.Interfaces;
using System.Windows;
using Microsoft.Extensions.Options;
using MinoChat.Models;

namespace MinoChat.Services;

// 主题服务实现，负责主题的应用和切换
public class ThemeService : IThemeService, IDisposable
{
    private ThemeMode _currentMode;
    private readonly IConfigService _configService;
    private readonly SystemThemeWatcher _themeWatcher;

    public ThemeService(IConfigService configService, SystemThemeWatcher themeWatcher)
    {
        _configService = configService;
        _themeWatcher = themeWatcher;
        // 从配置文件加载保存的主题模式
        var savedMode = _configService.GetThemeMode();
        // string格式化Enum如果成功取出就返回配置文件的Mode，否则就返回Auto
        _currentMode = Enum.TryParse<ThemeMode>(savedMode, out var mode) ? mode : ThemeMode.Auto;
    }

    // 应用指定的主题模式
    public void ApplyTheme(ThemeMode mode)
    {
        _currentMode = mode;
        // 将修改同步到配置文件
        _configService.SetThemeMode(mode.ToString());

        // 如果是Auto模式，订阅系统主题变化并启动监控
        if (mode == ThemeMode.Auto)
        {
            _themeWatcher.SystemThemeChanged += OnSystemThemeChanged;
            _themeWatcher.StartWatching();
            // 立即应用当前系统主题
            var systemTheme = SystemThemeWatcher.GetSystemTheme();
            ApplyActualTheme(systemTheme);
        }
        else
        {
            // 非Auto模式，取消订阅并停止监控
            _themeWatcher.SystemThemeChanged -= OnSystemThemeChanged;
            _themeWatcher.StopWatching();
            ApplyActualTheme(mode);
        }
    }

    // 系统主题变化时的处理
    private void OnSystemThemeChanged(object? sender, ThemeMode newThemeMode)
    {
        // 只有在Auto模式下才响应系统主题变化
        if (_currentMode == ThemeMode.Auto)
        {
            ApplyActualTheme(newThemeMode);
        }
    }

    // 应用实际的主题（将主项目的主题枚举转换为UI层主题枚举）
    private void ApplyActualTheme(ThemeMode actualTheme)
    {
        // 【1】主项目:重新应用对应的主题资源
        ApplyThemeResources(actualTheme);

        // 【2】第三方UI库:修改WPF-UI控件库的主题
        var wpfUiTheme = actualTheme switch
        {
            ThemeMode.Dark => Wpf.Ui.Appearance.ApplicationTheme.Dark,
            ThemeMode.Light => Wpf.Ui.Appearance.ApplicationTheme.Light,
            _ => Wpf.Ui.Appearance.ApplicationTheme.Light
        };
        Wpf.Ui.Appearance.ApplicationThemeManager.Apply(wpfUiTheme);

        // 【3】自定义UI库:修改MinoUI控件库的主题
        var minoUiTheme = actualTheme switch
        {
            ThemeMode.Dark => MinoChat.Ui.Enums.ThemeMode.Dark,
            ThemeMode.Light => MinoChat.Ui.Enums.ThemeMode.Light,
            _ => MinoChat.Ui.Enums.ThemeMode.Light
        };
        MinoChat.Ui.ThemeManager.Apply(minoUiTheme);

        // 【4】MarkdownView库:修改MarkdView控件库的主题
        var markdViewTheme = actualTheme switch
        {
            ThemeMode.Dark => MarkdView.Enums.ThemeMode.Dark,
            ThemeMode.Light => MarkdView.Enums.ThemeMode.Light,
            _ => MarkdView.Enums.ThemeMode.Light
        };
        MarkdView.ThemeManager.ApplyTheme(markdViewTheme);
    }

    // 应用主题资源字典到应用程序
    private void ApplyThemeResources(ThemeMode theme)
    {
        // 根据主题确定资源文件名
        var themeName = theme switch
        {
            ThemeMode.Dark => "DarkTheme.xaml",
            ThemeMode.Light => "LightTheme.xaml",
            _ => "LightTheme.xaml"
        };

        var themeUri = new Uri($"Resources/Themes/{themeName}", UriKind.Relative);
        var resources = Application.Current.Resources;

        // 移除已存在的主题资源字典
        var existingDictionary = resources.MergedDictionaries
            .FirstOrDefault(d => d.Source?.OriginalString.Contains("Theme.xaml") == true);

        if (existingDictionary != null)
        {
            resources.MergedDictionaries.Remove(existingDictionary);
        }

        // 添加新的主题资源字典
        var newDictionary = new ResourceDictionary { Source = themeUri };
        resources.MergedDictionaries.Add(newDictionary);
    }

    // 获取当前主题模式
    public ThemeMode GetCurrentThemeMode()
    {
        return _currentMode;
    }

    // 字符串转主题模式
    public ThemeMode ConvertStringToThemeMode(string theme)
    {
        return theme switch
        {
            "浅色" => ThemeMode.Light,
            "深色" => ThemeMode.Dark,
            "跟随系统" => ThemeMode.Auto,
            _ => ThemeMode.Light
        };
    }

    // 主题模式转字符串
    public string ConvertThemeModeToString(ThemeMode mode)
    {
        return mode switch
        {
            ThemeMode.Light => "浅色",
            ThemeMode.Dark => "深色",
            ThemeMode.Auto => "跟随系统",
            _ => "浅色"
        };
    }

    // 释放资源
    public void Dispose()
    {
        // 取消订阅并停止监控
        _themeWatcher.SystemThemeChanged -= OnSystemThemeChanged;
        _themeWatcher.StopWatching();
        GC.SuppressFinalize(this);
    }
}
